import { errorRoutes, constantRoutes } from '@/router/index.js';
import { permissionRoutes } from "@/utils/tools.js";
import Layout from '@/layout';

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes, errorRoutes);
  },
  RESET_STATE:(state) => {
    state.routes = [];
    state.addRoutes = [];
  }
}

const actions = {
  getAsyncRoutes({ commit }, roleInfo){
    return new Promise(async (resolve) => {
      const permissionIds = new Set();
      for(let i = 0; i < roleInfo.length; i ++){
        for(let j = 0; roleInfo[i].menuIds.length !== 0 && j < roleInfo[i].menuIds.length; j ++){
          permissionIds.add(roleInfo[i].menuIds[j])
        }
      }
      let permissionIdsArr = Array.from(permissionIds);
      let tmp = permissionRoutes.filter(item => permissionIdsArr.includes(item.id));
      let list = [];
      for(let k = 0; k < tmp.length; k ++){
        list.push(tmp[k].router);
      }
      resolve(list);
      commit("SET_ROUTES", list);
    })
  },
  resetState(permissionStore) {
    permissionStore.commit("RESET_STATE");
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

